package com.bozhong.robot.bar.barcounter;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.bozhong.robot.bar.barcounter.ui.BaseActivity;
import com.bozhong.robot.bar.barcounter.ui.ImageCache;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class Main2Activity extends BaseActivity {

    private static final String TAG = Main2Activity.class.getSimpleName();
    WebSocket ws;
    private String url = "http://192.168.104.125:8000";
    private Handler handler = new Handler();

    private ImageView iv_big;
    private ImageView iv_small;
    private ImageView iv_small2;
    private TextView tv_test_info;
    private TextView tv_connect_status;

    private String connected = "已连接";
    private String disconnected = "未连接";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        iv_big = (ImageView) findViewById(R.id.iv_big);
        iv_small = (ImageView) findViewById(R.id.iv_small);
        iv_small2 = (ImageView) findViewById(R.id.iv_small2);
        tv_test_info = (TextView) findViewById(R.id.tv_test_info);
        tv_connect_status = (TextView) findViewById(R.id.tv_connect_status);
        tv_connect_status.setText(disconnected);

        init();
    }

    @Override
    protected void onDestroy() {
        if (ws != null) {
            ws.disconnect();
        }
        super.onDestroy();
    }

    private void init() {
        try {
            ws = new WebSocketFactory().createSocket(url, 15) //ws地址，和设置超时时间
                    .setFrameQueueSize(5)//设置帧队列最大值为5
                    .setMissingCloseFrameAllowed(false)//设置不允许服务端关闭连接却未发送关闭帧
                    .addListener(new WsListener())//添加回调监听
                    .connectAsynchronously();//异步连接
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
     * onTextMessage 收到文字信息
     * onConnected 连接成功
     * onConnectError 连接失败
     * onDisconnected 连接关闭
     */
    class WsListener extends WebSocketAdapter {
        @Override
        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            super.onTextMessage(websocket, text);
            Log.i(TAG, text);
            final JSONObject jsonObject = new JSONObject(text);
            ImageCache.getInstance().loadBitmap(jsonObject.optString("PersonImgBase64"), iv_big);
            ImageCache.getInstance().loadBitmap(jsonObject.optString("BlkImgBase64"), iv_small);
            ImageCache.getInstance().loadBitmap(jsonObject.optString("FaceImgBase64"), iv_small2);

            handler.post(new Runnable() {
                @Override
                public void run() {
                    tv_test_info.setText("姓名：" + jsonObject.optString("Name") + "\n" + "证件号：" + jsonObject.optString("BlacklistID")
                            + "\n" + "相似度：" + jsonObject.optString("Similarity")
                    );
                }
            });
        }

        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
                throws Exception {
            super.onConnected(websocket, headers);
            Log.i(TAG, "连接成功");
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tv_connect_status.setText(connected);
                }
            });
        }

        @Override
        public void onConnectError(WebSocket websocket, WebSocketException exception)
                throws Exception {
            super.onConnectError(websocket, exception);
            Log.w(TAG, "连接错误：" + exception.getMessage());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    init();
                }
            }, 10000);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tv_connect_status.setText(disconnected);
                }
            });
        }

        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
                throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            Log.w(TAG, "断开连接");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ws.connectAsynchronously();
                }
            }, 10000);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    tv_connect_status.setText(disconnected);
                }
            });
        }

    }
}
